package com.stylefeng.guns.rest.modular.wz.api.v1;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.toolkit.IdWorker;
import com.stylefeng.guns.rest.common.base.controller.ApiBaseController;
import com.stylefeng.guns.rest.common.exception.BizExceptionEnum;
import com.stylefeng.guns.rest.common.persistence.dao.*;
import com.stylefeng.guns.rest.common.persistence.model.*;
import com.stylefeng.guns.rest.domain.ParamMap;
import com.stylefeng.guns.rest.domain.Res;
import com.stylefeng.guns.rest.enums.EnWzCoupon;
import com.stylefeng.guns.rest.enums.EnWzPrize;
import com.stylefeng.guns.rest.enums.EnWzUserFinanceRecord;
import com.stylefeng.guns.rest.modular.auth.util.JwtTokenUtil;
import com.stylefeng.guns.rest.modular.wz.cache.CacheService;
import com.stylefeng.guns.rest.modular.wz.service.impl.WzPrizeServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.*;

/**
 * 奖品表 前端控制器
 */
@RestController
@RequestMapping("/wz/api/v1/wzPrize/")
public class WzPrizeApi extends ApiBaseController {

    @Autowired
    private WzPrizeWinnersMapper prizeWinnersMapper;
    @Autowired
    private WzPrizeMapper prizeMapper;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private WzUserMapper userMapper;
    @Autowired
    private WzCouponMapper couponMapper;
    @Autowired
    private WzUserCouponMapper userCouponMapper;
    @Autowired
    private WzUserFinanceRecordMapper userFinanceRecordMapper;
    @Autowired
    private CacheService cacheService;
    @Autowired
    private WzPrizeServiceImpl prizeService;
    @Autowired
    private WzSysMapper sysMapper;

    /**
     * 抽奖页面
     */
//    @PostMapping("prizeList")
//    public Res prizeList(@RequestBody ParamMap paramMap){
//        List<Map<String,Object>> prizeList = new ArrayList<>();
//        String iosVersion = paramMap.getStr("iosVersion");
//        //奖品列表
//        String prizeSql = "prize_id As prizeId,title As title,subtitle As subtitle,cover_url As coverUrl,label As label,exchange_amount As exchangeAmount,status,prize_ratio As prizeRatio";
//        List<Map<String,Object>>  prizeLists = prizeMapper.selectMaps(new EntityWrapper<WzPrize>().setSqlSelect(prizeSql).in("status", new Integer[]{EnWzPrize.STATUS_RELEASE.getIndex(),EnWzPrize.STATUS_DOWN.getIndex()}).eq("type",EnWzPrize.TYPE_Prize_Coupon.getIndex()).orderBy("sort",true).orderBy("create_time",false).gt("sort",0));
//        List<WzSys> wzSys = sysMapper.selectList(new EntityWrapper<WzSys>());
//        if(wzSys.get(0).getIosStatus() == 0 && wzSys.get(0).getIosCheckVersion().equals(iosVersion)){
//            prizeLists = prizeMapper.selectMaps(new EntityWrapper<WzPrize>().setSqlSelect(prizeSql).in("status", new Integer[]{EnWzPrize.STATUS_RELEASE.getIndex(),EnWzPrize.STATUS_DOWN.getIndex()}).eq("type",EnWzPrize.TYPE_Prize_Coupon.getIndex()).orderBy("sort",true).orderBy("create_time",false).eq("is_show",1).gt("sort",0));
//        }
//        for(Map<String,Object>  map:prizeLists){
//            Map m = new HashMap();
//            m.put("prize",map);
//            //奖品获奖名单列表
//            List<Map<String,Object>>  prizeWinnersSqlList = prizeWinnersMapper.selectMapsPage(new Page<>(1,8),new EntityWrapper<WzPrizeWinners>().eq("prize_id", map.get("prizeId")).orderBy("winning_time",false));
//            m.put("prizeWinners",prizeWinnersSqlList);
//            int prizeWinnerNumber = prizeWinnersMapper.selectCount(new EntityWrapper<WzPrizeWinners>().eq("prize_id", map.get("prizeId")));
//            m.put("prizeWinnerNumber",prizeWinnerNumber);
//            prizeList.add(m);
//        }
//        return Res.success(prizeList);
//    }

    /**
     * 抽奖页面
     */
    @PostMapping("prizeLists")
    public Res prizeLists(@RequestBody ParamMap paramMap){
        int pageNum = paramMap.getIntMisValid("pageNum");
        int pageSize = paramMap.getIntMisValid("pageSize");
        List<Map<String,Object>> prizeList = new ArrayList<>();
        String iosVersion = paramMap.getStr("iosVersion");
        //奖品列表
        List<Map<String,Object>>  prizeLists = prizeMapper.selectMapsPage(new Page<>(pageNum,pageSize),new EntityWrapper<WzPrize>().in("status", new Integer[]{EnWzPrize.STATUS_RELEASE.getIndex(),EnWzPrize.STATUS_DOWN.getIndex()}).eq("type",EnWzPrize.TYPE_Prize_Coupon.getIndex()).orderBy("sort",true).orderBy("create_time",false).gt("sort",0));
        List<WzSys> wzSys = sysMapper.selectList(new EntityWrapper<WzSys>());
        if(wzSys.get(0).getIosStatus() == 0 && wzSys.get(0).getIosCheckVersion().equals(iosVersion)){
            prizeLists = prizeMapper.selectMapsPage(new Page<>(pageNum,pageSize),new EntityWrapper<WzPrize>().in("status", new Integer[]{EnWzPrize.STATUS_RELEASE.getIndex(),EnWzPrize.STATUS_DOWN.getIndex()}).eq("type",EnWzPrize.TYPE_Prize_Coupon.getIndex()).orderBy("sort",true).orderBy("create_time",false).eq("is_show",1).gt("sort",0));
        }
        for(Map<String,Object>  map:prizeLists){
            Map m = new HashMap();
            m.put("prize",map);
            //奖品获奖名单列表
            List<Map<String,Object>>  prizeWinnersSqlList = prizeWinnersMapper.selectMapsPage(new Page<>(1,8),new EntityWrapper<WzPrizeWinners>().eq("prize_id", map.get("prizeId")).orderBy("winning_time",false));
            m.put("prizeWinners",prizeWinnersSqlList);
            int prizeWinnerNumber = prizeWinnersMapper.selectCount(new EntityWrapper<WzPrizeWinners>().eq("prize_id", map.get("prizeId")));
            m.put("prizeWinnerNumber",prizeWinnerNumber);
            prizeList.add(m);
        }
        return Res.success(paramMap.data(prizeList));
    }

    /**
     * 获奖名单列表
     */
    @PostMapping("winnersList")
    public Res winnersList(@RequestBody ParamMap paramMap){
        int pageNum = paramMap.getIntMisValid("pageNum");
        int pageSize = paramMap.getIntMisValid("pageSize");
        String prizeId = paramMap.getStrMisValid("prizeId");
        //奖品获奖名单列表
        List<Map<String,Object>>  prizeWinners = prizeWinnersMapper.selectMapsPage(new Page<>(pageNum,pageSize),new EntityWrapper<WzPrizeWinners>().eq("prize_id", prizeId).orderBy("winning_time",false));
        paramMap.put("list",prizeWinners);
        return Res.success(paramMap);
    }



    /**
     * 奖品详情
     */
    @PostMapping("prize.detail")
    public Res prizeDetail(@RequestBody ParamMap paramMap){
        String prizeId = paramMap.getStrMisValid("prizeId");
        //奖品
        String prizeSql = "prize_id As prizeId,details As details,pay_amount As payAmount,exchange_amount As exchangeAmount,content_type As contentType,content,prize_ratio As prizeRatio";
        List<Map<String,Object>>  prizeLists = prizeMapper.selectMaps(new EntityWrapper<WzPrize>().setSqlSelect(prizeSql).eq("prize_id", prizeId));
        return Res.success(prizeLists.get(0));
    }

    /**
     * 用户中奖列表
     */
    @PostMapping("prize.record")
    public Res prizeRecord(@RequestBody ParamMap paramMap){
        int pageNum = paramMap.getIntMisValid("pageNum");
        int pageSize = paramMap.getIntMisValid("pageSize");
        String userCode = paramMap.getStrMisValid("userCode");
        //奖品
        List<WzPrizeWinners>  prizeWinnersList = prizeWinnersMapper.selectPage(new Page<>(pageNum,pageSize),new EntityWrapper<WzPrizeWinners>().eq("user_code", userCode).orderBy("winning_time",false));
        paramMap.put("list",prizeWinnersList);
        return Res.success(paramMap);
    }


    /**
     * 商城页面
     */
    @PostMapping("shopping.index")
    public Res shoppingIndex(@RequestBody ParamMap paramMap){
        int pageNum = paramMap.getIntMisValid("pageNum");
        int pageSize = paramMap.getIntMisValid("pageSize");
        String title = paramMap.getStrValid("title");
        String sql = "cover_url As coverUrl,prize_id As prizeId,title As title,subtitle As subtitle,exchange_amount As exchangeAmount,stock As stock";
        List<Map<String,Object>>  prizeList = prizeMapper.selectMapsPage(new Page<>(pageNum,pageSize),new EntityWrapper<WzPrize>().setSqlSelect(sql).eq("type",2).like("title",title));
        paramMap.put("list",prizeList);
        return Res.success(paramMap);
    }

    /**
     * 商城详细页面
     */
    @PostMapping("shopping.sublist")
    public Res shoppingSublist(@RequestBody ParamMap paramMap){
        int pageNum = paramMap.getIntMisValid("pageNum");
        int pageSize = paramMap.getIntMisValid("pageSize");
        int subtype = paramMap.getIntMisValid("subtype");
        String sql = "cover_url As coverUrl,prize_id As prizeId,title As title,subtitle As subtitle,exchange_amount As exchangeAmount,stock As stock";
        List<Map<String,Object>>  prizeList = prizeMapper.selectMapsPage(new Page<>(pageNum,pageSize),new EntityWrapper<WzPrize>().setSqlSelect(sql).eq("type",2).eq("subtype",subtype));
        paramMap.put("list",prizeList);
        return Res.success(paramMap);
    }

    /**
     * 商城积分兑换
     */
    @PostMapping("prize.exchange")
    public Res prizeExchange(@RequestBody ParamMap paramMap){
        String prizeId = paramMap.getStrMisValid("prizeId");
        int type = paramMap.getIntMisValid("type");//1-积分兑换；2-现金购买；
        Long userCode = jwtTokenUtil.getUserCodeFromToken();
        List<WzUser> userList = userMapper.selectList(new EntityWrapper<WzUser>().eq("user_code",userCode));
        WzPrize prize = prizeMapper.selectById(prizeId);
        if(type == 1 && userList.get(0).getRewardBalance() < prize.getExchangeAmount()){
            return Res.fail("积分不足!");
        }else if(type == 2 && userList.get(0).getCashBalance() < prize.getExchangeAmount()){
            return Res.fail("余额不足,请充值!");
        }
        if(prize.getStock() <= 0){
            return Res.fail("库存不足!");
        }
        return Res.success(paramMap);
    }

    /**
     * 开始抽奖 draw
     */
    @PostMapping("prize.draw")
    public Res prizeDraw(@RequestBody ParamMap paramMap){
        String prizeId = paramMap.getStrMisValid("prizeId");
        Long userCode = jwtTokenUtil.getUserCodeFromToken();
        WzUser user = cacheService.user(userCode);
        if(user.getStatus() == 0){
            return Res.fail("账户资金异常，冻结中!");
        }
        WzPrize prize = prizeMapper.selectById(prizeId);
        prize.setPrizeNumber(prize.getPrizeNumber() + 1);
        if(prize.getStatus() == EnWzPrize.STATUS_DOWN.getIndex() || prize.getStock() <= 0){
            paramMap.clear();
            paramMap.put("userCouponId","");
            paramMap.put("rewardBalance",user.getRewardBalance());
            return Res.fail(BizExceptionEnum.PRIZE_Invalid.getCode(),"奖品已失效!",paramMap);
        }
        if(user.getRewardBalance() < prize.getPayAmount()){
            paramMap.clear();
            paramMap.put("userCouponId","");
            paramMap.put("rewardBalance",user.getRewardBalance());
            return Res.fail(BizExceptionEnum.PRIZE_NO_reward_balance.getCode(),"积分不足!",paramMap);
        }
        //用户资金处理
        user.setRewardBalance(user.getRewardBalance() - prize.getPayAmount());
        if(user.getRewardBalance() < 0){
            user.setRewardBalance(0);
        }
        //中奖判断
        String s = prize.getRatio();
        int position = s.length() - 2;
        int a = 1;
        if(position == 2 || position == 1){
            a = 100;
        }else if(position == 3){
            a = 1000;
        }else if(position == 4){
            a = 10000;
        }else{
            //资金记录
            WzUserFinanceRecord userFinanceRecord = new WzUserFinanceRecord();
            userFinanceRecord.setId(IdWorker.getId());
            userFinanceRecord.setTargetId(userFinanceRecord.getId().toString());//唯一id号
            userFinanceRecord.setAmount(prize.getPayAmount());
            userFinanceRecord.setCreateTime(new Date());
            userFinanceRecord.setPayTime(new Date());
            userFinanceRecord.setPayMethod(EnWzUserFinanceRecord.payMethod_wz.getIndex());
            userFinanceRecord.setType(EnWzUserFinanceRecord.TYPE_OUT.getIndex());
            userFinanceRecord.setStatus(EnWzUserFinanceRecord.STATUS_SUCCESS.getIndex());
            userFinanceRecord.setTitle(EnWzUserFinanceRecord.TITLE_prize_draw.getName());
            userFinanceRecord.setRemark("奖品id:"+prizeId);
            userFinanceRecord.setUserCode(userCode);
            userFinanceRecord.setPayType(EnWzUserFinanceRecord.TITLE_prize_draw.getIndex());
            userFinanceRecord.setCashBalance(user.getCashBalance());
            userFinanceRecord.setRewardBalance(user.getRewardBalance());
            userFinanceRecord.setProfit(user.getProfit());
            boolean r = prizeService.savePrizeFail(prize,user,userFinanceRecord);
            if(r){
                paramMap.clear();
                paramMap.put("userCouponId","");
                paramMap.put("rewardBalance",user.getRewardBalance());
                return Res.fail(BizExceptionEnum.PRIZE_NO_WINNING.getCode(),"很遗憾，没中奖!",paramMap);
            }else{
                return Res.fail();
            }
        }
        Random rand = new Random();
        int num = rand.nextInt(a);
        int ratio = new BigDecimal(prize.getRatio()).multiply(new BigDecimal(a)).intValue();
        //中奖处理
        if(0<num && num <= ratio){
//            int p = prize.getExchangeAmount()/20000;
//            int c = userFinanceRecordMapper.selectCount(new EntityWrapper<WzUserFinanceRecord>().eq("user_code",userCode).like("remark",prizeId.toString()));
//            if(p >= c){
//                return Res.fail();
//            }
            List<WzCoupon> couponList = couponMapper.selectList(new EntityWrapper<WzCoupon>().eq("prize_id",prizeId));
            WzPrizeWinners prizeWinners = new WzPrizeWinners();
            prizeWinners.setAvatarUrl(user.getAvatarUrl());
            prizeWinners.setWinningTime(new Date());
            prizeWinners.setNickName(user.getNickName());
            prizeWinners.setUserCode(userCode);
            prizeWinners.setCoverUrl(prize.getCoverUrl());
            prizeWinners.setLabel(prize.getLabel());
            prizeWinners.setTitle(prize.getTitle());
            prizeWinners.setSubtitle(prize.getSubtitle());
            prizeWinners.setPrizeId(Long.parseLong(prizeId));
            WzUserCoupon userCoupon = new WzUserCoupon();
            userCoupon.setUserCouponId(IdWorker.getId());
            userCoupon.setUserCode(userCode);
            userCoupon.setType(EnWzCoupon.TYPE_Prize.getIndex());
            userCoupon.setStatus(1);
            userCoupon.setCreateTime(new Date());
            userCoupon.setCouponId(couponList.get(0).getCouponId());
            userCoupon.setPrizeId(couponList.get(0).getPrizeId());
            userCoupon.setBeginTime(couponList.get(0).getBeginTime());
            userCoupon.setEndTime(couponList.get(0).getEndTime());
            userCoupon.setSubtype(couponList.get(0).getSubtype());
            userCoupon.setAdvMapId(couponList.get(0).getAdvMapId());
            userCoupon.setPic(couponList.get(0).getPic());
            userCoupon.setRule(couponList.get(0).getRule());
            userCoupon.setAvatarUrl(user.getAvatarUrl());
            userCoupon.setNickName(user.getNickName());
            userCoupon.setName(couponList.get(0).getMerchantName());
            userCoupon.setLogo(couponList.get(0).getLogo());
            prize.setStock(prize.getStock() -1);
            if(prize.getStock() <= 0){
                prize.setStatus(EnWzPrize.STATUS_DOWN.getIndex());
            }
            //资金记录
            WzUserFinanceRecord userFinanceRecord = new WzUserFinanceRecord();
            userFinanceRecord.setId(IdWorker.getId());
            userFinanceRecord.setTargetId(userFinanceRecord.getId().toString());//唯一id号
            userFinanceRecord.setAmount(prize.getPayAmount());
            userFinanceRecord.setCreateTime(new Date());
            userFinanceRecord.setPayTime(new Date());
            userFinanceRecord.setType(EnWzUserFinanceRecord.TYPE_OUT.getIndex());
            userFinanceRecord.setStatus(EnWzUserFinanceRecord.STATUS_SUCCESS.getIndex());
            userFinanceRecord.setTitle(EnWzUserFinanceRecord.TITLE_prize_draw.getName());
            userFinanceRecord.setRemark("奖品id:"+prizeId);
            userFinanceRecord.setUserCode(userCode);
            userFinanceRecord.setPayType(EnWzUserFinanceRecord.TITLE_prize_draw.getIndex());
            userFinanceRecord.setCashBalance(user.getCashBalance());
            userFinanceRecord.setRewardBalance(user.getRewardBalance());
            userFinanceRecord.setProfit(user.getProfit());
            boolean r = prizeService.savePrizeWinner(userFinanceRecord,prizeWinners,userCoupon,prize,user);
            if(r){
                paramMap.clear();
                paramMap.put("couponId",userCoupon.getCouponId());
                paramMap.put("userCouponId",userCoupon.getUserCouponId());
                paramMap.put("rewardBalance",user.getRewardBalance());
                return Res.success(paramMap);
            }else{
                return Res.fail();
            }
        }else{//没中奖
            //资金记录
            WzUserFinanceRecord userFinanceRecord = new WzUserFinanceRecord();
            userFinanceRecord.setId(IdWorker.getId());
            userFinanceRecord.setTargetId(userFinanceRecord.getId().toString());//唯一id号
            userFinanceRecord.setAmount(prize.getPayAmount());
            userFinanceRecord.setCreateTime(new Date());
            userFinanceRecord.setPayTime(new Date());
            userFinanceRecord.setType(EnWzUserFinanceRecord.TYPE_OUT.getIndex());
            userFinanceRecord.setStatus(EnWzUserFinanceRecord.STATUS_SUCCESS.getIndex());
            userFinanceRecord.setTitle(EnWzUserFinanceRecord.TITLE_prize_draw.getName());
            userFinanceRecord.setRemark("奖品id:"+prizeId);
            userFinanceRecord.setUserCode(userCode);
            userFinanceRecord.setPayType(EnWzUserFinanceRecord.TITLE_prize_draw.getIndex());
            userFinanceRecord.setCashBalance(user.getCashBalance());
            userFinanceRecord.setRewardBalance(user.getRewardBalance());
            userFinanceRecord.setProfit(user.getProfit());
            boolean r = prizeService.savePrizeFail(prize,user,userFinanceRecord);
            if(r){
                paramMap.clear();
                paramMap.put("userCouponId","");
                paramMap.put("rewardBalance",user.getRewardBalance());
                return Res.fail(BizExceptionEnum.PRIZE_NO_WINNING.getCode(),"很遗憾，没中奖!",paramMap);
            }else{
                return Res.fail();
            }
        }
    }

}

